//
//  Untitled001ViewController.m
//  Untitled001
//
//  Created by gyo on 10. 12. 2..
//  Copyright 2010 com2us. All rights reserved.
//

#define FORMAT(format, ...) [NSString stringWithFormat:(format), ##__VA_ARGS__]

#import "Untitled001ViewController.h"
#import "AsyncSocket.h"
#import "JSON.h"

@implementation Untitled001ViewController
@synthesize m_UIConnectButton;
@synthesize m_UILabel;
@synthesize m_UISendText;
@synthesize m_UIRecvText;
@synthesize m_UISendResult;

- (id) init
{
	if(self = [super init])
	{
		listenSocket = [[AsyncSocket alloc] initWithDelegate:self];
		
		m_bConnect = NO;
		
		[m_UILabel setText:@"InitValue"];
	}
	return self;
}

- (void)viewDidLoad {
	[self init];
	[super viewDidLoad];
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[m_UIConnectButton release];
	[m_UILabel release];
	[m_UISendText release];
	[m_UIRecvText release];
	[m_UISendResult release];
    [super dealloc];
}

- (IBAction)backgroundClick:(id)sender
{
	[m_UISendText resignFirstResponder];
	[m_UIRecvText resignFirstResponder];
}

- (void)logInfo:(NSString *)msg
{
//	NSString *paragraph = [NSString stringWithFormat:@"%@\n", msg];
//	
//	NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:1];
//	[attributes setObject:[NSColor purpleColor] forKey:NSForegroundColorAttributeName];
//	
//	NSAttributedString *as = [[NSAttributedString alloc] initWithString:paragraph attributes:attributes];
//	[as autorelease];
//	
//	[[logView textStorage] appendAttributedString:as];
//	[self scrollToBottom];
}


- (IBAction)startStop:(id)sender
{
	if(!m_bConnect)
	{
		
		NSError *error = nil;

		
		//BOOL bResult = [listenSocket connectToHost:@"127.0.0.1" onPort:1111 error:&error];
		BOOL bResult = [listenSocket connectToHost:@"127.0.0.1" onPort:1111 error:&error];
		if(bResult == YES)
		{
			m_bConnect = YES;
			
			[m_UILabel setText:@"ON"];
			
			[m_UIConnectButton setTitle:@"UnConnect" forState:UIControlStateNormal];
		}
	}
	else
	{
		[listenSocket disconnect];
		m_bConnect = false;
		
		[m_UILabel setText:@"OFF"];
		
		[m_UIConnectButton setTitle:@"Connect" forState:UIControlStateNormal];

	}
}

- (IBAction)sendText:(id)sender
{
	if(m_bConnect)
	{
		//NSString *welcomeMsg = [m_UISendText text];
		//NSString *welcomeMsg = @"Welcome to the AsyncSocket Echo Server\r\n";
		NSString *welcomeMsg = @"TestString\r\n";
		NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding];
		
		[listenSocket writeData:welcomeData withTimeout:-1 tag:0];
		[m_UISendResult setText:welcomeMsg];
		
	}
	else {
		[m_UISendResult setText:@"UnConnect"];
	}
}
		 


- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
//	[self logInfo:FORMAT(@"Accepted client %@:%hu", host, port)];
//	
//	NSString *welcomeMsg = @"Welcome to the AsyncSocket Echo Server\r\n";
//	NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding];
//	
//	[sock writeData:welcomeData withTimeout:-1 tag:0];
	
	// We could call readDataToData:withTimeout:tag: here - that would be perfectly fine.
	// If we did this, we'd want to add a check in onSocket:didWriteDataWithTag: and only
	// queue another read if tag != WELCOME_MSG.
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
	[sock readDataToData:[AsyncSocket CRLFData] withTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
	NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
	NSString *msg = [[[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding] autorelease];
	if(msg)
	{
		[m_UIRecvText setText:msg];
		//[m_UIRecvText setText:@"TESTRECV"];
		//[self logMessage:msg];
	}
	else
	{
		[m_UIRecvText setText:@"TEST"];
		//[self logError:@"Error converting received data into UTF-8 String"];
	}
	
	// Even if we were unable to write the incoming data to the log,
	// we're still going to echo it back to the client.
	//[sock writeData:data withTimeout:-1 tag:1];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
	[self logInfo:FORMAT(@"Client Disconnected: %@:%hu", [sock connectedHost], [sock connectedPort])];
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
	//[connectedSockets removeObject:sock];
}


- (NSString*) stringWithUrl:(NSURL*)url
{
	NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
	
	//Fetch the JSON response
	NSData *urlData;
	NSURLResponse *response;
	NSError *error;
	
	//Make synchronous request
	urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
	
	//Construct a String around the Data from the response
	return [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding] autorelease];
}

- (IBAction) getJSONwithNet:(id)sender
{
	//NSString *strResponse = [self stringWithUrl:[NSURL URLWithString:@"http://www.google.com/ig/cities?country=kr&hl=en"]];
	NSString *strResponse = [self stringWithUrl:[NSURL URLWithString:@"http://alones.kr/iphone/test/test.html"]];
	[m_UISendText setText:strResponse];
	
	//Create BSJSON parser
	SBJSON *jsonParser = [[[SBJSON alloc] init] autorelease];
	
	//Get the result dictionary from the response string.
	NSDictionary *dic = (NSDictionary*)[jsonParser objectWithString:strResponse error:NULL];
	
	//Show response
	//Key and value type
	NSLog(@"firstName: %@", [dic objectForKey:@"firstName"]);
	NSLog(@"lastName: %@", [dic objectForKey:@"lastName"]);
	
	//한글 테스트
	NSLog(@"한글이름 : %@", [dic objectForKey:@"한글이름"]);
	
	//Key and Dictionary as its value type
	NSDictionary *addressDic = [dic objectForKey:@"address"];
	NSLog(@"address : streetAddress: %@", [addressDic objectForKey:@"streetAddress"]);
	NSLog(@"address : city: %@", [addressDic objectForKey:@"city"]);
	NSLog(@"address : state: %@", [addressDic objectForKey:@"state"]);
	NSLog(@"address : postalCode: %@", [addressDic objectForKey:@"postalCode"]);
	
	//Key and Array as its value type
	//array에는 type과 number로 된 dictionary가 들어 있음
	NSArray *phoneArray = [dic objectForKey:@"phoneNumbers"];
	for(int i = 0; i < [phoneArray count]; i++)
	{
		NSLog(@"phoneNumbers: type: %@", [[phoneArray objectAtIndex:i] objectForKey:@"type"]);
		NSLog(@"phoneNumbers: number: %@", [[phoneArray objectAtIndex:i] objectForKey:@"number"]);
	}	
}

@end
